import { useReducer, createContext } from "react";
import { ItemProp } from "../components/BasicItem";
import { LineProp } from "../components/Line";

interface InitState {
  data: ItemProp[];
  lines: LineProp[];
}

const initContext: {
  state: InitState;
  dispatch: Function;
} = {
  state: { data: [], lines: [] },
  dispatch: () => {},
};

const ReducerContext = createContext(initContext);

interface UnitAction {
  type: "unit";
  x: string;
  y: string;
  index: number;
}

interface ListAction {
  type: "all";
  data: ItemProp[];
}

function reducer(state: InitState, action: UnitAction | ListAction) {
  let copyData = Object.assign({}, state);
  if (action.type === "unit") {
    const { x, y, index } = action;
    copyData.data[index].x = x;
    copyData.data[index].y = y;
  } else {
    copyData.data = action.data;
  }
  return copyData;
}

const initialState: InitState = {
  data: [],
  lines: [
    {
      from: { nodeIndex: 0, anchorPotion: "right" },
      to: { nodeIndex: 1, anchorPotion: "left" },
    },
  ],
};

export default function ReducerProvider(props: any) {
  const [state, dispatch] = useReducer(reducer, initialState);
  return (
    <ReducerContext.Provider value={{ state, dispatch }}>
      {props.children}
    </ReducerContext.Provider>
  );
}

export { ReducerContext };
